#include "com_a_testapi23_MainActivity.h"
#include <time.h>
#include <android/log.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <pthread.h>
#include <stdlib.h>


typedef unsigned long long u64;

u64 get_cur_tm()
{
    struct timeval tm;
    gettimeofday(&tm, NULL);
    u64 ms = 0;
    if(tm.tv_usec < 1000000)
        ms = tm.tv_usec / 1000;
    return ((u64)tm.tv_sec) * 1000 + ms;
}

u64 last = 0;

void p()
{
    u64 now = get_cur_tm();
    u64 diff = now - last;
    __android_log_print(ANDROID_LOG_ERROR, "sleep_jni ", "cur =%lld", diff);
    last = now;

}

JNIEXPORT void JNICALL Java_com_a_testapi23_MainActivity_GetString
        (JNIEnv *env, jobject obj)
{
    static int used = 0;
    if( used == 1 )
        return;
    used = 1;
    signal(SIGALRM, p);
    struct itimerval value;
    value.it_value.tv_sec = 5;
    value.it_value.tv_usec = 0;
    value.it_interval.tv_sec = 5;
    value.it_interval.tv_usec = 0;
    last = get_cur_tm();
    setitimer(ITIMER_REAL, &value, NULL);
    while(1)
    {
    //    __android_log_print(ANDROID_LOG_ERROR, "sleep_jni ", "cur =%ld", get_cur_tm());
       pause();
       //p();
       //sleep(5);

    }
}

volatile int running = 0;
void* task_speed()
{
    while(running)
    {

    }

}

pthread_t pid_speed[100];
int cnt = 0;
JNIEXPORT void JNICALL Java_com_a_testapi23_MainActivity_startjni
        (JNIEnv *env, jobject obj)
{

    int i;
    running = 1;
    cnt = rand()%80 + 20;
    for(i=0; i<cnt; i++) {
        pthread_create(&(pid_speed[i]), NULL, task_speed, NULL);
    }
}
JNIEXPORT void JNICALL Java_com_a_testapi23_MainActivity_stopjni
        (JNIEnv *env, jobject obj)
{
    int i;
    running = 0;
    void* p;
    for(i=0; i<cnt; i++) {
        pthread_join(pid_speed[i], &p);
    }
}
